package com.cn.yunhe.rentcars.web;

import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cn.yunhe.rentcars.captcah.BCaptcha;
import com.cn.yunhe.rentcars.captcah.ImageCode;

/**
 * 验证码生成，和校验 controller
 * @author 赵志学
 * 2016-8-3
 *
 */
@RestController
@RequestMapping("")
public class KaptchaController {
	BCaptcha instance = new BCaptcha();
	/**
	 * 获取验证码，并传递显示到页面。
	 * @param request
	 * @param response
	 */
	@RequestMapping("/codeImage")
	public void codeImage1(HttpServletRequest request, HttpServletResponse response) {
		// 设置不缓存图片
		  try {	
			  	response.setHeader("Pragma", "No-cache");
				response.setHeader("Cache-Control", "No-cache");
				response.setDateHeader("Expires", 0);
				// 指定生成的响应图片,一定不能缺少这句话,否则错误.
				response.setContentType("image/jpeg");				
				HttpSession session = request.getSession();
		        ImageCode result = instance.getImageCode();
		        ImageIO.write((RenderedImage) result.getImage(), "png", response.getOutputStream());
				
		  } catch (IOException e) {			
				e.printStackTrace();
		}
	}
	/**
	 * 验证码校验，
	 * @param verifyCode
	 * @return
	 */
	@RequestMapping(value="/checkCode",method=RequestMethod.GET)
	public Map<String,String> checkCode(@RequestParam String verifyCode){
		String resultData;		
		String checkValue = instance.getCv();		
		String code = verifyCode;
		 if(code.equalsIgnoreCase(checkValue)){
			 //System.out.println("验证成功");
			 resultData = "Y";
		 }else{
			// System.out.println("验证码错误");
			 resultData = "N";
		 }
           Map<String,String>map = new HashMap<String,String>();
           map.put("resultData", resultData);		 
           return map;
	}
}
